<template>
<div class="system-message-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar 
        title="系统通知" 
        left-arrow 
        @click-left="onClickLeft" 
        fixed
        right-text="清空"
        @click-right="onClearAll"
    />
    
    <div class="content">
        <!-- 下拉刷新 -->
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh" success-text="刷新成功">
            <!-- 加载中状态 -->
            <div class="loading-container" v-if="loading">
                <van-loading type="spinner" color="#ff2442" />
            </div>
            
            <!-- 空状态 -->
            <div class="empty-state" v-else-if="isEmpty">
                <van-empty image="search" description="暂无系统消息" />
            </div>
            
            <!-- 消息列表 -->
            <div class="message-list" v-else>
                <div 
                    class="message-item" 
                    v-for="item in systemMessages" 
                    :key="item.id" 
                    @click="openMessage(item)"
                    :class="{'unread': !item.isRead}"
                >
                    <div class="message-icon" :class="getIconClass(item.icon)">
                        <van-icon :name="item.icon" size="24" />
                    </div>
                    
                    <div class="message-content">
                        <div class="message-header">
                            <span class="message-title">{{ item.title }}</span>
                            <span class="message-time">{{ formatTime(item.time) }}</span>
                        </div>
                        
                        <div class="message-body">
                            {{ item.content }}
                        </div>
                    </div>
                    
                    <div class="message-actions">
                        <van-icon name="delete-o" size="18" @click.stop="deleteMessage(item)" />
                    </div>
                </div>
                
                <!-- 加载更多 -->
                <div class="load-more" v-if="hasMore" @click="loadMore">
                    <van-loading v-if="loadingMore" type="spinner" size="20" />
                    <span v-else>加载更多</span>
                </div>
                
                <!-- 无更多数据 -->
                <div class="no-more" v-else-if="!isEmpty">
                    <span>没有更多数据了</span>
                </div>
            </div>
        </van-pull-refresh>
    </div>
    
    <!-- 清空确认弹窗 -->
    <van-dialog
        v-model="showClearDialog"
        title="清空系统消息"
        message="确定要清空所有系统消息吗？此操作不可恢复。"
        show-cancel-button
        @confirm="clearAllMessages"
    />
</div>
</template>

<script>
import { defineComponent } from 'vue'
import { Toast } from 'vant'
import { messageApi } from '@/api/message'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'

// 配置dayjs使用相对时间插件
dayjs.extend(relativeTime)

export default defineComponent({
    name: 'SystemMessagePage',
    
    data() {
        return {
            // 系统消息数据
            systemMessages: [],
            // 是否正在加载
            loading: false,
            // 是否正在下拉刷新
            refreshing: false,
            // 是否正在加载更多
            loadingMore: false,
            // 是否有更多数据
            hasMore: true,
            // 当前页码
            page: 1,
            // 每页数据量
            pageSize: 10,
            // 是否显示清空确认弹窗
            showClearDialog: false
        }
    },
    
    computed: {
        // 是否为空状态
        isEmpty() {
            return this.systemMessages.length === 0
        }
    },
    
    created() {
        // 获取消息数据
        this.fetchMessages()
    },
    
    methods: {
        // 返回上一页
        onClickLeft() {
            this.$router.back()
        },
        
        // 点击清空按钮
        onClearAll() {
            if (this.isEmpty) {
                Toast('暂无消息可清空')
                return
            }
            
            this.showClearDialog = true
        },
        
        // 清空所有消息
        async clearAllMessages() {
            try {
                await messageApi.clearAllMessages('system')
                
                // 清空列表
                this.systemMessages = []
                
                // 更新store中的未读消息数
                this.$store.commit('setNotifications', 0)
                
                Toast('已清空所有系统消息')
            } catch (error) {
                console.error('清空消息失败', error)
                Toast('操作失败，请重试')
            }
        },
        
        // 获取消息
        async fetchMessages(isLoadMore = false) {
            if (!isLoadMore) {
                this.loading = true
                this.page = 1
            } else {
                this.loadingMore = true
            }
            
            try {
                const params = {
                    page: this.page,
                    pageSize: this.pageSize
                }
                
                const data = await messageApi.getSystemMessages(params)
                
                if (isLoadMore) {
                    // 加载更多，追加数据
                    this.systemMessages = [...this.systemMessages, ...data.list]
                } else {
                    // 初次加载或刷新，替换数据
                    this.systemMessages = data.list || []
                }
                
                // 更新是否有更多数据
                this.hasMore = data.hasMore
                
                // 页码加1
                this.page++
            } catch (error) {
                console.error('获取系统消息失败', error)
                Toast('获取消息失败，请重试')
            } finally {
                this.loading = false
                this.loadingMore = false
                this.refreshing = false
            }
        },
        
        // 下拉刷新
        onRefresh() {
            this.fetchMessages()
        },
        
        // 加载更多
        loadMore() {
            if (this.loadingMore || !this.hasMore) return
            this.fetchMessages(true)
        },
        
        // 打开消息
        async openMessage(item) {
            // 标记为已读
            if (!item.isRead) {
                try {
                    await messageApi.markAsRead({ type: 'system', id: item.id })
                    
                    // 更新消息状态
                    item.isRead = true
                    
                    // 更新store中的未读消息数
                    this.updateUnreadCount()
                } catch (error) {
                    console.error('标记已读失败', error)
                }
            }
            
            // 如果有链接则跳转
            if (item.link) {
                this.$router.push(item.link)
            }
        },
        
        // 删除消息
        async deleteMessage(item) {
            try {
                await messageApi.deleteMessage(item.id)
                
                // 从列表中删除该消息
                const index = this.systemMessages.findIndex(msg => msg.id === item.id)
                if (index !== -1) {
                    this.systemMessages.splice(index, 1)
                }
                
                // 如果删除的是未读消息，更新未读计数
                if (!item.isRead) {
                    this.updateUnreadCount()
                }
                
                Toast('已删除消息')
            } catch (error) {
                console.error('删除消息失败', error)
                Toast('操作失败，请重试')
            }
        },
        
        // 更新未读消息计数
        updateUnreadCount() {
            // 计算未读消息数量
            const unreadCount = this.systemMessages.filter(item => !item.isRead).length
            
            // 更新store
            this.$store.commit('setNotifications', unreadCount)
        },
        
        // 获取图标的CSS类名
        getIconClass(icon) {
            const iconMap = {
                'bell': 'notice-icon',
                'chat-o': 'chat-icon',
                'gem-o': 'activity-icon',
                'gift-o': 'gift-icon',
                'balance-o': 'wallet-icon',
                'info-o': 'info-icon',
                'warning-o': 'warning-icon'
            }
            
            return iconMap[icon] || 'default-icon'
        },
        
        // 格式化时间
        formatTime(time) {
            if (!time) return ''
            
            const now = dayjs()
            const messageTime = dayjs(time)
            
            // 如果是今天
            if (now.isSame(messageTime, 'day')) {
                return messageTime.format('HH:mm')
            }
            
            // 如果是昨天
            if (now.subtract(1, 'day').isSame(messageTime, 'day')) {
                return '昨天 ' + messageTime.format('HH:mm')
            }
            
            // 如果是本周
            if (now.isSame(messageTime, 'week')) {
                const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
                return weekdays[messageTime.day()]
            }
            
            // 如果是今年
            if (now.isSame(messageTime, 'year')) {
                return messageTime.format('MM-DD')
            }
            
            // 其他情况
            return messageTime.format('YYYY-MM-DD')
        }
    }
})
</script>

<style scoped>
.system-message-container {
    min-height: 100vh;
    background-color: #f7f8fa;
}

.content {
    padding-top: 46px;
    min-height: calc(100vh - 46px);
}

.loading-container {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 40px 0;
}

.empty-state {
    padding: 40px 0;
}

.message-list {
    background-color: #fff;
}

.message-item {
    display: flex;
    padding: 16px;
    border-bottom: 1px solid #f5f5f5;
    position: relative;
}

.message-item.unread::before {
    content: '';
    position: absolute;
    top: 16px;
    right: 16px;
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background-color: #ff2442;
}

.message-icon {
    width: 46px;
    height: 46px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 12px;
    flex-shrink: 0;
}

.notice-icon {
    background-color: #e6f7ff;
    color: #1989fa;
}

.chat-icon {
    background-color: #e8faf0;
    color: #07c160;
}

.activity-icon {
    background-color: #fff2e8;
    color: #fa8c16;
}

.gift-icon {
    background-color: #fff0f6;
    color: #eb2f96;
}

.wallet-icon {
    background-color: #fcf4e8;
    color: #faad14;
}

.info-icon {
    background-color: #e6f7ff;
    color: #1989fa;
}

.warning-icon {
    background-color: #fff2f0;
    color: #ff4d4f;
}

.default-icon {
    background-color: #f2f3f5;
    color: #909399;
}

.message-content {
    flex: 1;
    overflow: hidden;
}

.message-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 4px;
}

.message-title {
    font-size: 15px;
    font-weight: 500;
    color: #333;
}

.message-time {
    font-size: 12px;
    color: #999;
}

.message-body {
    font-size: 14px;
    color: #666;
    line-height: 1.5;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}

.message-actions {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 30px;
    margin-left: 12px;
    color: #999;
    flex-shrink: 0;
}

.load-more, .no-more {
    text-align: center;
    padding: 16px;
    color: #999;
    font-size: 14px;
}
</style> 